import React, { useState } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  InputNumber,
  Button,
  message,
  Row,
  Col,
  Table,
  Tag,
  Space,
  Typography,
  Alert,
  Statistic,
  Progress,
  Modal,
  Tabs,
  DatePicker,
  Slider,
  Divider,
  Timeline,
  Badge
} from 'antd';
import {
  PlayCircleOutlined,
  PauseCircleOutlined,
  ReloadOutlined,
  DownloadOutlined,
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  SettingOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { Title, Paragraph } = Typography;
const { TabPane } = Tabs;

const StrategyBacktest = () => {
  const [form] = Form.useForm();
  const [backtestResults, setBacktestResults] = useState([]);
  const [isRunning, setIsRunning] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedResult, setSelectedResult] = useState(null);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);

  // 模拟回测结果数据
  const mockBacktestResults = [
    {
      id: 1,
      name: '价值成长混合策略回测',
      strategy: '价值成长混合策略',
      startDate: '2023-01-01',
      endDate: '2024-01-01',
      initialCapital: 100000,
      finalValue: 118500,
      totalReturn: 18.5,
      annualReturn: 18.5,
      maxDrawdown: -8.2,
      sharpeRatio: 1.45,
      volatility: 12.8,
      winRate: 65.2,
      status: 'completed',
      createTime: '2024-01-15'
    },
    {
      id: 2,
      name: '量化择时策略回测',
      strategy: '量化择时策略',
      startDate: '2023-06-01',
      endDate: '2024-01-01',
      initialCapital: 100000,
      finalValue: 112300,
      totalReturn: 12.3,
      annualReturn: 18.9,
      maxDrawdown: -12.5,
      sharpeRatio: 1.23,
      volatility: 15.2,
      winRate: 58.7,
      status: 'completed',
      createTime: '2024-01-10'
    },
    {
      id: 3,
      name: '低风险稳健策略回测',
      strategy: '低风险稳健策略',
      startDate: '2023-03-01',
      endDate: '2024-01-01',
      initialCapital: 100000,
      finalValue: 108200,
      totalReturn: 8.2,
      annualReturn: 9.8,
      maxDrawdown: -3.5,
      sharpeRatio: 1.67,
      volatility: 6.8,
      winRate: 72.3,
      status: 'running',
      createTime: '2024-01-20'
    }
  ];

  const handleStartBacktest = async () => {
    try {
      const values = await form.validateFields();
      setIsRunning(true);
      message.info('回测正在运行中，请稍候...');
      
      // 模拟回测过程
      setTimeout(() => {
        const newResult = {
          id: Date.now(),
          name: `${values.strategyName}回测`,
          strategy: values.strategyName,
          startDate: values.dateRange[0].format('YYYY-MM-DD'),
          endDate: values.dateRange[1].format('YYYY-MM-DD'),
          initialCapital: values.initialCapital,
          finalValue: Math.floor(values.initialCapital * (1 + Math.random() * 0.3)),
          totalReturn: Math.random() * 30,
          annualReturn: Math.random() * 25,
          maxDrawdown: -(Math.random() * 15),
          sharpeRatio: 0.8 + Math.random() * 1.2,
          volatility: 8 + Math.random() * 12,
          winRate: 50 + Math.random() * 30,
          status: 'completed',
          createTime: new Date().toISOString().split('T')[0]
        };
        
        setBacktestResults([newResult, ...backtestResults]);
        setIsRunning(false);
        message.success('回测完成！');
      }, 3000);
    } catch (error) {
      console.error('回测启动失败:', error);
    }
  };

  const handleViewDetail = (record) => {
    setSelectedResult(record);
    setIsDetailModalVisible(true);
  };

  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个回测结果吗？删除后无法恢复。',
      onOk: () => {
        setBacktestResults(backtestResults.filter(result => result.id !== id));
        message.success('删除成功');
      },
    });
  };

  const columns = [
    {
      title: '回测名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '策略',
      dataIndex: 'strategy',
      key: 'strategy',
      width: 150,
      render: (strategy) => <Tag color="blue">{strategy}</Tag>,
    },
    {
      title: '回测期间',
      key: 'period',
      width: 200,
      render: (_, record) => `${record.startDate} ~ ${record.endDate}`,
    },
    {
      title: '初始资金',
      dataIndex: 'initialCapital',
      key: 'initialCapital',
      width: 120,
      render: (value) => `¥${value.toLocaleString()}`,
    },
    {
      title: '最终价值',
      dataIndex: 'finalValue',
      key: 'finalValue',
      width: 120,
      render: (value) => `¥${value.toLocaleString()}`,
    },
    {
      title: '总收益率',
      dataIndex: 'totalReturn',
      key: 'totalReturn',
      width: 120,
      render: (value) => (
        <span style={{ color: value >= 0 ? '#52c41a' : '#ff4d4f' }}>
          {value >= 0 ? '+' : ''}{value.toFixed(1)}%
        </span>
      ),
    },
    {
      title: '年化收益',
      dataIndex: 'annualReturn',
      key: 'annualReturn',
      width: 120,
      render: (value) => (
        <span style={{ color: value >= 0 ? '#52c41a' : '#ff4d4f' }}>
          {value >= 0 ? '+' : ''}{value.toFixed(1)}%
        </span>
      ),
    },
    {
      title: '最大回撤',
      dataIndex: 'maxDrawdown',
      key: 'maxDrawdown',
      width: 120,
      render: (value) => (
        <span style={{ color: '#ff4d4f' }}>
          {value.toFixed(1)}%
        </span>
      ),
    },
    {
      title: '夏普比率',
      dataIndex: 'sharpeRatio',
      key: 'sharpeRatio',
      width: 100,
      render: (value) => value.toFixed(2),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Badge 
          status={status === 'completed' ? 'success' : 'processing'} 
          text={status === 'completed' ? '已完成' : '运行中'} 
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="link" 
            size="small" 
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          <Button 
            type="link" 
            size="small" 
            icon={<DownloadOutlined />}
          >
            导出
          </Button>
          <Button 
            type="link" 
            size="small" 
            danger 
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Title level={3}>策略回测与模拟</Title>
      <Paragraph type="secondary">对策略进行历史回测和模拟交易，评估策略表现</Paragraph>

      <Row gutter={24}>
        {/* 左侧：回测配置 */}
        <Col span={8}>
          <Card 
            title={
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <SettingOutlined style={{ marginRight: '8px', color: '#1890ff' }} />
                <span>回测配置</span>
              </div>
            }
            style={{ marginBottom: '24px' }}
          >
            <Form
              form={form}
              layout="vertical"
              initialValues={{
                initialCapital: 100000,
                transactionCost: 0.1,
                slippage: 0.05
              }}
            >
              <Form.Item
                name="strategyName"
                label="策略名称"
                rules={[{ required: true, message: '请输入策略名称' }]}
              >
                <Input placeholder="请输入策略名称" />
              </Form.Item>

              <Form.Item
                name="dateRange"
                label="回测期间"
                rules={[{ required: true, message: '请选择回测期间' }]}
              >
                <RangePicker style={{ width: '100%' }} />
              </Form.Item>

              <Form.Item
                name="initialCapital"
                label="初始资金"
                rules={[{ required: true, message: '请输入初始资金' }]}
              >
                <InputNumber
                  min={1000}
                  max={10000000}
                  style={{ width: '100%' }}
                  placeholder="请输入初始资金"
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value.replace(/\¥\s?|(,*)/g, '')}
                />
              </Form.Item>

              <Form.Item
                name="transactionCost"
                label="交易成本(%)"
                rules={[{ required: true, message: '请输入交易成本' }]}
              >
                <InputNumber
                  min={0}
                  max={5}
                  step={0.01}
                  style={{ width: '100%' }}
                  placeholder="请输入交易成本"
                />
              </Form.Item>

              <Form.Item
                name="slippage"
                label="滑点(%)"
                rules={[{ required: true, message: '请输入滑点' }]}
              >
                <InputNumber
                  min={0}
                  max={5}
                  step={0.01}
                  style={{ width: '100%' }}
                  placeholder="请输入滑点"
                />
              </Form.Item>

              <Form.Item
                name="rebalanceFrequency"
                label="再平衡频率"
                rules={[{ required: true, message: '请选择再平衡频率' }]}
              >
                <Select placeholder="请选择再平衡频率">
                  <Option value="daily">每日</Option>
                  <Option value="weekly">每周</Option>
                  <Option value="monthly">每月</Option>
                  <Option value="quarterly">每季度</Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="benchmark"
                label="基准指数"
                rules={[{ required: true, message: '请选择基准指数' }]}
              >
                <Select placeholder="请选择基准指数">
                  <Option value="000300">沪深300</Option>
                  <Option value="000905">中证500</Option>
                  <Option value="399006">创业板指</Option>
                  <Option value="000016">上证50</Option>
                </Select>
              </Form.Item>

              <Button
                type="primary"
                icon={isRunning ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
                onClick={handleStartBacktest}
                loading={isRunning}
                style={{ width: '100%' }}
                disabled={isRunning}
              >
                {isRunning ? '回测中...' : '开始回测'}
              </Button>
            </Form>
          </Card>

          {/* 模拟交易 */}
          <Card 
            title={
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <BarChartOutlined style={{ marginRight: '8px', color: '#52c41a' }} />
                <span>模拟交易</span>
              </div>
            }
          >
            <Alert
              message="模拟交易"
              description="基于当前策略进行实时模拟交易，验证策略有效性"
              type="info"
              showIcon
              style={{ marginBottom: '16px' }}
            />
            <Space direction="vertical" style={{ width: '100%' }}>
              <Button type="primary" style={{ width: '100%' }}>启动模拟交易</Button>
              <Button style={{ width: '100%' }}>查看模拟结果</Button>
            </Space>
          </Card>
        </Col>

        {/* 右侧：回测结果 */}
        <Col span={16}>
          <Card 
            title={
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <LineChartOutlined style={{ marginRight: '8px', color: '#1890ff' }} />
                  <span>回测结果</span>
                </div>
                <Space>
                  <Button icon={<ReloadOutlined />}>刷新</Button>
                  <Button icon={<DownloadOutlined />}>批量导出</Button>
                </Space>
              </div>
            }
          >
            <Table
              dataSource={backtestResults}
              columns={columns}
              rowKey="id"
              pagination={{ pageSize: 10 }}
              scroll={{ x: 1200 }}
            />
          </Card>
        </Col>
      </Row>

      {/* 回测详情模态框 */}
      <Modal
        title="回测详情"
        open={isDetailModalVisible}
        onCancel={() => setIsDetailModalVisible(false)}
        width={1000}
        footer={null}
      >
        {selectedResult && (
          <Tabs defaultActiveKey="1">
            <TabPane tab="收益分析" key="1">
              <Row gutter={24}>
                <Col span={12}>
                  <Card title="关键指标" size="small">
                    <Row gutter={16}>
                      <Col span={12}>
                        <Statistic
                          title="总收益率"
                          value={selectedResult.totalReturn}
                          suffix="%"
                          valueStyle={{ color: selectedResult.totalReturn >= 0 ? '#52c41a' : '#ff4d4f' }}
                        />
                      </Col>
                      <Col span={12}>
                        <Statistic
                          title="年化收益率"
                          value={selectedResult.annualReturn}
                          suffix="%"
                          valueStyle={{ color: selectedResult.annualReturn >= 0 ? '#52c41a' : '#ff4d4f' }}
                        />
                      </Col>
                    </Row>
                    <Row gutter={16} style={{ marginTop: '16px' }}>
                      <Col span={12}>
                        <Statistic
                          title="最大回撤"
                          value={selectedResult.maxDrawdown}
                          suffix="%"
                          valueStyle={{ color: '#ff4d4f' }}
                        />
                      </Col>
                      <Col span={12}>
                        <Statistic
                          title="夏普比率"
                          value={selectedResult.sharpeRatio}
                          valueStyle={{ color: '#faad14' }}
                        />
                      </Col>
                    </Row>
                    <Row gutter={16} style={{ marginTop: '16px' }}>
                      <Col span={12}>
                        <Statistic
                          title="胜率"
                          value={selectedResult.winRate}
                          suffix="%"
                          valueStyle={{ color: '#52c41a' }}
                        />
                      </Col>
                      <Col span={12}>
                        <Statistic
                          title="波动率"
                          value={selectedResult.volatility}
                          suffix="%"
                          valueStyle={{ color: '#1890ff' }}
                        />
                      </Col>
                    </Row>
                  </Card>
                </Col>
                <Col span={12}>
                  <Card title="收益走势" size="small">
                    <div style={{ height: '200px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999' }}>
                      <div>
                        <LineChartOutlined style={{ fontSize: '48px', marginBottom: '16px' }} />
                        <p>收益走势图表</p>
                      </div>
                    </div>
                  </Card>
                </Col>
              </Row>
            </TabPane>
            <TabPane tab="交易记录" key="2">
              <Table
                dataSource={[
                  { date: '2024-01-15', action: '买入', fund: '华夏成长混合', shares: 1000, price: 1.25, amount: 1250 },
                  { date: '2024-01-14', action: '卖出', fund: '易方达消费行业', shares: 500, price: 1.52, amount: 760 },
                  { date: '2024-01-13', action: '买入', fund: '嘉实增长混合', shares: 800, price: 1.22, amount: 976 }
                ]}
                columns={[
                  { title: '日期', dataIndex: 'date', key: 'date' },
                  { title: '操作', dataIndex: 'action', key: 'action', render: (action) => <Tag color={action === '买入' ? 'green' : 'red'}>{action}</Tag> },
                  { title: '基金', dataIndex: 'fund', key: 'fund' },
                  { title: '份额', dataIndex: 'shares', key: 'shares' },
                  { title: '价格', dataIndex: 'price', key: 'price', render: (price) => `¥${price}` },
                  { title: '金额', dataIndex: 'amount', key: 'amount', render: (amount) => `¥${amount}` }
                ]}
                pagination={false}
                size="small"
              />
            </TabPane>
            <TabPane tab="风险分析" key="3">
              <Row gutter={24}>
                <Col span={12}>
                  <Card title="回撤分析" size="small">
                    <div style={{ height: '200px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999' }}>
                      <div>
                        <BarChartOutlined style={{ fontSize: '48px', marginBottom: '16px' }} />
                        <p>回撤分析图表</p>
                      </div>
                    </div>
                  </Card>
                </Col>
                <Col span={12}>
                  <Card title="风险指标" size="small">
                    <Row gutter={16}>
                      <Col span={12}>
                        <Statistic title="VaR(95%)" value={-2.8} suffix="%" />
                      </Col>
                      <Col span={12}>
                        <Statistic title="CVaR(95%)" value={-4.2} suffix="%" />
                      </Col>
                    </Row>
                    <Row gutter={16} style={{ marginTop: '16px' }}>
                      <Col span={12}>
                        <Statistic title="Beta" value={0.85} />
                      </Col>
                      <Col span={12}>
                        <Statistic title="Alpha" value={2.3} suffix="%" />
                      </Col>
                    </Row>
                  </Card>
                </Col>
              </Row>
            </TabPane>
          </Tabs>
        )}
      </Modal>
    </div>
  );
};

export default StrategyBacktest; 